package com.androidproject.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONArray;
import org.json.JSONObject;

import com.androidproject.Constantes;
import com.androidproject.LineAdapterNews;
import com.androidproject.R;
import com.androidproject.modele.Article;
import com.androidproject.modele.News;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
	
	private Intent intentAccueil;
	private Intent intentClassement;
	private Intent intentCalendrier;
	private Intent intentProgrammeTV;
	private Intent intentFacebook;
	private Intent intentTwitter;
	private Intent intentDetailArticle;
	private News news;
	private ProgressDialog progressD;
	
	public class TaskObject extends AsyncTask<String, Void, StringBuffer> {

		private HttpResponse response;
		private JSONObject jSonObject;
		
		@Override
		//String... pour sp�cifier qu'il n'y a pas de nombre de param�tre sp�cifique, il faut juste que ce soit le m�me type
		protected StringBuffer doInBackground(String... url) {
			
			StringBuffer chaine = new StringBuffer("");
			
			try{
				
				AndroidHttpClient client = AndroidHttpClient.newInstance("user-agent"); 
				URI uri = new URI(url[0]);
				HttpGet request = new HttpGet(); 
				request.setURI(uri); 
				response = client.execute(request); 
				client.close();
				
				// Get the response 
				InputStream inputStream = response.getEntity().getContent(); 
				BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); 
				String line = "";
				
				while ((line = rd.readLine()) != null) { 
					chaine.append(line);
				} 
				
			} catch(Exception e){ 
				chaine.append(e.getMessage());
				
			} finally { } 
			
			return chaine;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			progressD = ProgressDialog.show(MainActivity.this, Constantes.WAIT_TITLE,Constantes.WAIT_MESSAGE_NEWS, true);
		}
		
		@Override
		protected void onPostExecute(StringBuffer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			progressD.dismiss();
			
			try{ //Traitement du JSON 
				
				jSonObject = new JSONObject(result.toString()); //result.toString().replaceFirst("\\r\\t\\n", ""));
//				JSONObject resultatNews = jSonObject.getJSONObject(Constantes.NEWS);
				JSONArray resultatNews = new JSONArray(jSonObject.getString(Constantes.NEWS));
//				JSONArray articles = new JSONArray(resultatNews.getString(""));
				
				news = new News();
				
				for (int i = 0; i < resultatNews.length(); i++) {
					
					Article article = new Article(resultatNews.getJSONObject(i).getString(Constantes.NEWS_TITRE), 
													resultatNews.getJSONObject(i).getString(Constantes.NEWS_DATE), 
													resultatNews.getJSONObject(i).getString(Constantes.NEWS_IMAGE), 
													resultatNews.getJSONObject(i).getString(Constantes.NEWS_CONTENT), 
													resultatNews.getJSONObject(i).getString(Constantes.NEWS_DESCRIPTION));
							news.getArticleList().add(article);
				}
				
				ListView listView = (ListView) findViewById(R.id.ListViewNews);
				listView.setAdapter(new LineAdapterNews(MainActivity.this, news.getArticleList()));
				
				listView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
						
						Article selectedArticle = (Article)arg0.getItemAtPosition(arg2);
						intentDetailArticle.putExtra("article", selectedArticle);
						startActivity(intentDetailArticle);
					}
				});
				
			} catch(Exception e){ 
				Log.e("Erreur",e.getMessage()); 
//				for (int i = 0; i < e.getStackTrace().length; i++) {
//					Log.d("catch erreur", e.getStackTrace()[i].toString());
//				}
			} finally { } 
			
		}
	}
	
//	public class myTask extends AsyncTask<String, Void, StringBuffer> {
//
//		@Override
//		protected StringBuffer doInBackground(String... arg0) {
//			
//			StringBuffer chaine = new StringBuffer("");
//			
//			try{
//				
//				AndroidHttpClient client = AndroidHttpClient.newInstance("user-agent"); 
//				URI uri = new URI("http://webservices.handnews.fr/tmthandnews.php"); 
//				HttpGet request = new HttpGet(); 
//				request.setURI(uri); 
//				response = client.execute(request); 
//				client.close(); 
//				// Get the response 
//				InputStream inputStream = response.getEntity().getContent(); 
//				BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); 
//				String line = "";
//				while ((line = rd.readLine()) != null) { 
////					textview.append(line); // 2 
//					chaine.append(line);
//					System.out.println(line);
//				} 
//			}catch(Exception e){ 
////				textview.setText(e.getMessage()); // 3 
//				chaine.append(e.getMessage());
//			}finally { } // 4
//				
//			
//			return chaine;
//		} 
//	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
//		setContentView(R.layout.activity_detail_article);
		
		intentDetailArticle = new Intent(this, DetailArticleActivity.class);

		TaskObject task = new TaskObject(); 
		task.execute(new String[] {Constantes.FLUX_NEWS});
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.

//		MenuInflater inflater = getMenuInflater();
//		inflater.inflate(R.menu.menug, menu);
		
		menu.add(0, 1, 0, "News").setIcon(R.drawable.logo_journal);
		menu.add(0, 2, 0, "Classement").setIcon(R.drawable.logo_classement);
		menu.add(0, 3, 0, "Programme TV").setIcon(R.drawable.logo_tv);
		menu.add(0, 4, 0, "Calendrier").setIcon(R.drawable.logo_calendrier);
		menu.add(0, 5, 0, "Facebook").setIcon(R.drawable.logo_facebook);
		menu.add(0, 6, 0, "Twitter").setIcon(R.drawable.logo_twitter);
	    
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
			case 1:
				intentAccueil = new Intent(this, MainActivity.class);
				startActivity(intentAccueil);
				return true;
				
			case 2:
				intentClassement = new Intent(this, ClassementActivity.class);
				startActivity(intentClassement);
				return true;
				
			case 3:
				intentProgrammeTV = new Intent(this, ProgrammeTvActivity.class);
				startActivity(intentProgrammeTV);
				return true;
				
			case 4:
				intentCalendrier = new Intent(this, CalendrierActivity.class);
				startActivity(intentCalendrier);
				return true;
			
			case 5:
				intentFacebook = new Intent(this, FacebookActivity.class);
				startActivity(intentFacebook);
				return true;
				
			case 6:
				intentTwitter = new Intent(this, TwitterActivity.class);
				startActivity(intentTwitter);
				return true;
				
			default:
				return true;
		}
		
//		intentAccueil = 	new Intent(this, MainActivity.class);
//		intentClassement =	new Intent(this, ClassementActivity.class);
//		intentCalendrier = 	new Intent(this, CalendrierActivity.class);
//		intentProgrammeTV = new Intent(this, ProgrammeTvActivity.class);
//		intentFacebook = 	new Intent(this, FacebookActivity.class);
//		intentTwitter = 	new Intent(this, TwitterActivity.class);
//		
//		switch (item.getItemId()) {
//			case R.id.mAccueil:
//				startActivity(intentAccueil);
//				return true;
//			case R.id.mClassement:
//				startActivity(intentClassement);
//				return true;
//			case R.id.mCalendrier:
//				startActivity(intentCalendrier);
//				return true;
//			case R.id.mProgrammeTV:
//				startActivity(intentProgrammeTV);
//				return true;
//			case R.id.mFacebook:
//				startActivity(intentFacebook);
//				return true;
//			case R.id.mTwitter:
//				startActivity(intentTwitter);
//				return true;
//			default:
//				return true;
//		}
	}

}
